package com.sky.common.task;

import com.sky.business.sys.domain.AlarmRecord;
import com.sky.business.sys.domain.CameraConfig;
import com.sky.business.sys.service.AlarmRecordService;
import com.sky.business.sys.service.CameraConfigService;
import com.sky.business.sys.service.NVRDeviceService;
import com.sky.common.config.CacheConstants;
import com.sky.common.config.Config;
import com.sky.common.track.AlarmInfo;
import com.sky.common.track.AlarmManager;
import com.sky.common.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;

/**
 * 警报保存定时任务
 *
 */
@Slf4j
@Component
public class AlarmRecordSaveTask {

    @Autowired
    private CameraConfigService cameraConfigService;

    @Autowired
    private AlarmRecordService alarmRecordService;

    @Autowired
    private NVRDeviceService nvrDeviceService;


    /**
     * 入库
     * @param alarmInfo 警报信息
     */
    public void save(AlarmInfo alarmInfo){

        long seconds = DateUtils.secondPlus(alarmInfo.getBeginTime(),alarmInfo.getEndTime());
        if(seconds< CacheConstants.ALARM_MIN_DURATION_SECOND){
            log.info("警报时长小于{}秒,不保存",CacheConstants.ALARM_MIN_DURATION_SECOND);
            return;
        }
        CameraConfig cameraConfig = cameraConfigService.findByDeviceId(alarmInfo.getDeviceId());
        if(cameraConfig==null){
            log.error("设备不存在,设备ID:{}",alarmInfo.getDeviceId());
            return;
        }
        if(cameraConfig.getChannelno()==null || cameraConfig.getChannelno()==0){
            log.error("设备未设置nvr频道,设备ID:{}",cameraConfig.getCameraDeviceId());
            return;
        }
        AlarmRecord alarmRecord = alarmInfo.toAlarmRecord();
        alarmRecord.setCameraConfigId(cameraConfig.getId());
        alarmRecord.setChannelno(cameraConfig.getChannelno());
        alarmRecordService.save(alarmRecord);
        //nvr
        nvrDeviceService.processAlarmNvr(alarmRecord);
    }

    /**
     * 定时任务
     */
    @Scheduled(fixedDelay = 10000)
    public void doTask(){
        if(!Config.nvrEnable){
            return;
        }
        Date expireDate = DateUtils.from(LocalDateTime.now().plusSeconds(-CacheConstants.ALARM_INTERRUPT_SECOND));
        Iterator<Map.Entry<String, AlarmInfo>> iterator =  AlarmManager.iterator();
        while(iterator.hasNext()){
            Map.Entry<String, AlarmInfo> entry = iterator.next();
            AlarmInfo alarmInfo = entry.getValue();
            if(alarmInfo.getEndTime().before(expireDate)){
                iterator.remove();
                //入库
                save(alarmInfo);
            }
        }

    }
}
